package org.itboys.mobile.service.mysql.web.promotion;

import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.promotion.SundayCouponActivityMapper;
import org.itboys.mobile.dao.promotion.SundayCouponMapper;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.promotion.SundayCoupon;
import org.itboys.mobile.entity.mysql.promotion.SundayCouponActivity;
import org.itboys.mobile.service.mongo.mobile.SundayMobileMemberService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;

/**
 * 作者：zzq
 * 时间：2017年5月15日
 * 描述：圣代_促销管理_后台_service。含多种促销。当前只有优惠券促销
 */
@Service
public class SundayPromotionService {

    @Autowired
    private SundayCouponMapper couponMapper;
    @Autowired
    private SundayCouponActivityMapper couponActivityMapper;
    @Autowired
    private SundayMobileMemberService memberService;
    /****************************优惠券部分*******************/
    /**
     * 新增或修改优惠券活动
     * @param activity
     */
        public void saveActivity(SundayCouponActivity activity){
            if(activity.getId()==0l){
                couponActivityMapper.insert(activity);
            }else{
                couponActivityMapper.update(activity);
            }
        }

    /**
     * 分页查询优惠券活动
     * @param request
     * @return
     */
    public PageResult<SundayCouponActivity> selectActivity(HttpServletRequest request){
            Map<String,Object> param= ParamUtil.packageMysqlPageParam(request,"status");
           Serializable count = couponActivityMapper.count(param);
            return new PageResult<SundayCouponActivity>(couponActivityMapper.select(param),count==null?0l:Long.valueOf(count.toString()));
        }
    /**
     * 分页查询优惠券
     * @param request
     * @return
     */
    public PageResult<SundayCoupon> selectCoupon(HttpServletRequest request){
        Map<String,Object> param= ParamUtil.packageMysqlPageParam(request,"status","activityId");
        Serializable count = couponMapper.count(param);
        return new PageResult<SundayCoupon>(couponMapper.select(param),count==null?0l:Long.valueOf(count.toString()));
    }

    /**
     * 查找单个优惠券活动
     * @param id
     * @return
     */
    public SundayCouponActivity findOne(Long id){
        SundayCouponActivity activity=new SundayCouponActivity();
        activity.setId(0l);
        if(LongUtil.isNotZreo(id)){
            activity=couponActivityMapper.find(id);
        }
        return activity;
    }
    /**
     * 更改优惠券活动状态
     * @param activityId
     * @param status
     */
    public void changeCouponActivityStatus(Long activityId,Integer status){
        SundayCouponActivity activity= new SundayCouponActivity();
        activity.setId(activityId);
        activity.setStatus(status);
        couponActivityMapper.update(activity);
    }

    /**
     *注册时，自动发放优惠券
     * @param memberId
     */
    public void sendCouponByRegister(Long memberId){
        Map<String ,Object> param=new HashMap<String,Object>();
         SundayMember member=memberService.getById(memberId);
         param.put("type", SundayCommonConstants.PROMOTION_COUPON_TYPE_REGISTER);
         param.put("status", SundayCommonConstants.YES);
         //查询所有有效的
         List<SundayCouponActivity> activities=couponActivityMapper.select(param);
         if(ListUtil.isNotNull(activities)){
             //当前时间
             Date now=new Date();
             Integer currentDate=now.getDate();
             for(SundayCouponActivity activity:activities){
                 //生成优惠券的失效时间
                 now.setDate(currentDate+activity.getDay());
                 SundayCoupon coupon=new SundayCoupon(activity.getId(),activity.getType(),member.getId(),member.getNickName(),activity.getBaseAmount(),activity.getDecuAmount(),
                         SundayCommonConstants.counpon_status_wsy,"新用户注册赠送",now);
                 couponMapper.insert(coupon);
                 now.setDate(currentDate);
             }
         }
    }

    /**
     * 系统自动发送优惠券给所有用户
     *
     */
    public void sendCoupon(){
        Map<String,Object> param=new HashMap<String,Object>();

        param.put("type", SundayCommonConstants.PROMOTION_COUPON_TYPE_SYSTEM);
        param.put("status",SundayCommonConstants.YES);
        //所有有效的优惠券活动
        List<SundayCouponActivity> allActivities=couponActivityMapper.select(param);
        List<SundayCouponActivity> activities=new ArrayList<SundayCouponActivity>();
        //判断是否到发送优惠券的时间
        for(SundayCouponActivity activity:allActivities){
            if(activity.getSendTime().getTime()<new Date().getTime()){
                activities.add(activity);
            }
        }
        if(ListUtil.isNull(activities))return;
        //所有的用户优惠券（系统已经发放的）
        param.clear();
        param.put("type",SundayCommonConstants.PROMOTION_COUPON_TYPE_SYSTEM);
        List<SundayCoupon> doneCoupons=couponMapper.select(param);
        //所有用户
        param.clear();
        param.put("userType",SundayCommonConstants.user_type_member);
        List<SundayMember> members = memberService.list(param);

        //所有要发放的优惠券（包含已经发放过的用户）
        List<SundayCoupon> allCoupons = new ArrayList<SundayCoupon>();
        //本次真正要发放的优惠券。（去掉已经发放过的用户）
        List<SundayCoupon> realCoupons = new ArrayList<SundayCoupon>();
        //1,迭代出,要发送的所有优惠券。包含已经发放过的用户
        for(SundayCouponActivity activity:activities){
            Date now=new Date();
            Integer currentDate=now.getDate();
            for(SundayMember member:members){
                now.setDate(currentDate+activity.getDay());
                SundayCoupon coupon=new SundayCoupon(activity.getId(),activity.getType(),member.getId(),member.getNickName(),activity.getBaseAmount(),activity.getDecuAmount(),
                        SundayCommonConstants.counpon_status_wsy,"系统赠送",now);
                allCoupons.add(coupon);
                now.setDate(currentDate);
            }
        }
        //2,迭代要发放的所有优惠券和已经发放的记录。可以得到本次真正发放的优惠券数量
        for(SundayCoupon allCoupon:allCoupons){
            //是否发放
            boolean isSend=true;
            for(SundayCoupon doneCoupon:doneCoupons){
                if(allCoupon.getActivityId().longValue()==doneCoupon.getActivityId().longValue()&&
                        allCoupon.getMemberId().longValue()==doneCoupon.getMemberId().longValue()){
                    isSend=false;
                    break;
                }
            }
            if(isSend){
                realCoupons.add(allCoupon);
            }
        }
        //3,生成优惠券
        for(SundayCoupon realCoupon:realCoupons){
                    couponMapper.insert(realCoupon);
        }


    }
    /****************************优惠券部分结束*******************/
}
